package com.banyou.banyou.login.login;

import android.app.AlertDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.support.design.widget.TextInputEditText;
import android.support.design.widget.TextInputLayout;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.banyou.banyou.R;
import com.banyou.banyou.base.BaseActivity;
import com.banyou.banyou.bean.login.login.LoginBean;
import com.banyou.banyou.login.forget.ForgetActivity;
import com.banyou.banyou.login.regist.RegistActivity;
import com.banyou.banyou.main.MainActivity;
import com.banyou.banyou.util.ShowToast;
import com.banyou.banyou.webutils.ProgressSubscriber;
import com.socks.library.KLog;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * ----------Dragon be here!----------/
 * 　　　┏┓　　　┏┓
 * 　　┏┛┻━━━┛┻┓
 * 　　┃　　　　　　　┃
 * 　　┃　　　━　　　┃
 * 　　┃　┳┛　┗┳　┃
 * 　　┃　　　　　　　┃
 * 　　┃　　　┻　　　┃
 * 　　┃　　　　　　　┃
 * 　　┗━┓　　　┏━┛
 * 　　　　┃　　　┃神兽保佑
 * 　　　　┃　　　┃代码无BUG！
 * 　　　　┃　　　┗━━━┓
 * 　　　　┃　　　　　　　┣┓
 * 　　　　┃　　　　　　　┏┛
 * 　　　　┗┓┓┏━┳┓┏┛
 * 　　　　　┃┫┫　┃┫┫
 * 　　　　　┗┻┛　┗┻┛
 * ━━━━━━神兽出没━━━━━━
 * 类描述：
 * 创建人：Random
 * 修改时间：
 * 修改备注：
 */

public class LoginActivity extends BaseActivity<LoginPresenter> implements LoginContract.View,View.OnClickListener {


    @BindView(R.id.edit_username)
    TextInputEditText mEditUsername;
    @BindView(R.id.edit_username_content)
    TextInputLayout mEditUsernameContent;
    @BindView(R.id.edit_password)
    TextInputEditText mEditPassword;
    @BindView(R.id.edit_password_content)
    TextInputLayout mEditPasswordContent;
    @BindView(R.id.button_forget)
    TextView mButtonForget;
    @BindView(R.id.regist_button)
    TextView mRegistButton;
    Button mLoginButton;

    @Override
    protected LoginPresenter initPresenter() {
        return new LoginPresenter();
    }

    @Override
    protected int initLayout() {
        return R.layout.activity_login;
    }

    @Override
    protected View initLayoutView() {
        return null;
    }

    @Override
    protected void init() {
        mPresenter.initPresenter(this, new LoginModel());
        ButterKnife.bind(this);
        initEditText();//初始化EditText

    }

    /**
     * 初始化EditText
     */
    private void initEditText() {
        //用户名输入监听
        mEditUsername.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                mEditUsernameContent.setErrorEnabled(false);
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        //密码输入监听
        mEditPassword.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                mEditPasswordContent.setErrorEnabled(false);
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        //用户名回车监听
        mEditUsername.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                mEditPassword.requestFocus();
                return true;
            }
        });
        //密码回车键监听
        mEditPassword.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if(TextUtils.isEmpty(mEditUsername.getText())||TextUtils.isEmpty(mEditPassword.getText())){
                    Toast.makeText(LoginActivity.this,"请输入完整内容",Toast.LENGTH_SHORT).show();
                    return true;
                }
                //TODO 联网操作
                return true;
            }
        });
    }

    @Override
    protected String pageName() {
        return "登录页";
    }

    /**
     * 点击事件
     *
     * @param view
     */
    @OnClick({R.id.button_forget, R.id.regist_button,  R.id.login_button})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.button_forget:
                Intent forIntent=new Intent(this, ForgetActivity.class);
                startActivity(forIntent);
                break;
            case R.id.regist_button:
                createRegistDialog();
                break;
            case R.id.login_button:
                if(checkEditText()){//检测EditText
                    mPresenter.login(mEditUsername.getText().toString(),mEditPassword.getText().toString());
                }
                break;
            case R.id.accompanying_btn:
                Intent intent=new Intent(this, RegistActivity.class);
                intent.putExtra("type",2);//1代表伴游
                startActivity(intent);
                mAlertDialog.dismiss();
                break;
            case R.id.user_btn:
                Intent userIntent=new Intent(this,RegistActivity.class);
                userIntent.putExtra("type",1);//2代表游客
                startActivity(userIntent);
                mAlertDialog.dismiss();
                break;
        }
    }

    private AlertDialog mAlertDialog;

    /**
     * 生成注册dialog
     */
    private void createRegistDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("请选择您要注册的类型").setCancelable(true);
        View view = LayoutInflater.from(this).inflate(R.layout.activity_login_dialog, null);
        ViewHolder holder=new ViewHolder(view);
        holder.mUserBtn.setOnClickListener(this);
        holder.mAccompanyingBtn.setOnClickListener(this);
        builder.setView(view);
        mAlertDialog= builder.create();
        mAlertDialog.getWindow().setBackgroundDrawable(getResources().getDrawable(R.drawable.alert_dialog_alpha_drawable));
        mAlertDialog.show();
    }



    /**
     * 检测EditText,无误则可以登录
     */
    private boolean checkEditText() {
        String userName = mEditUsername.getText().toString();
        String password = mEditPassword.getText().toString();
        if (userName.trim().length() == 0) {
            mEditUsernameContent.setErrorEnabled(true);
            mEditUsernameContent.setError("请输入用户名");
            return false;
        }
        if (password.trim().length() == 0) {
            mEditPasswordContent.setErrorEnabled(true);
            mEditPassword.setError("请输入密码");
            return false;
        }
        if(!RegistActivity.isPhoneNum(userName)){
            Toast.makeText(this,"请输入正确的手机号",Toast.LENGTH_SHORT).show();
            return false;
        }
        return true;
    }

    /**
     * 登录成功
     */
    @Override
    public void loginSuccess(LoginBean bean) {
        SharedPreferences preferences=getSharedPreferences("login",MODE_PRIVATE);
        SharedPreferences.Editor editor=preferences.edit();
        editor.putString("userId",bean.getUserInfo().getUserId()+"");
        editor.putString("userType",bean.getUserInfo().getUserType());
        editor.putString("billId",bean.getUserInfo().getBillId());
        editor.apply();
        Toast.makeText(this,"登录成功",Toast.LENGTH_SHORT).show();
        Intent intent=new Intent(LoginActivity.this, MainActivity.class);
        startActivity(intent);
        this.finish();
    }

    /**
     * 登录失败
     */
    @Override
    public void loginFail(Throwable e) {
        if(e instanceof ProgressSubscriber.ReturnCodeErrorException){
            ShowToast.showToast(((ProgressSubscriber.ReturnCodeErrorException) e).getMsg());
        }else {
            Toast.makeText(this, "登录失败", Toast.LENGTH_SHORT).show();
        }
    }

    static class ViewHolder {
        @BindView(R.id.accompanying_btn)
        Button mAccompanyingBtn;
        @BindView(R.id.user_btn)
        Button mUserBtn;

        ViewHolder(View view) {
            ButterKnife.bind(this, view);
        }
    }
}
